package main

import (
	"fmt"
	"sync"
)

type DatabaseInterface interface {
	connect(dns string)
}

type MysqlConnector struct {
	name string
}

func (conn *MysqlConnector)connect(dns string) {
	fmt.Println("Connected to Mysql based on DNS string")
}

var once  sync.Once
var conn *MysqlConnector

func GetConnector() *MysqlConnector {
	once.Do(func () {
		conn = &MysqlConnector{name:"MySql Connector"}
		fmt.Println("Init database on DSN")
	})

	return conn
}

/*
* 实现思路，利用 sync.Once 来实现并发安全，进而来实现单例模式
* Java 里面的并发如何实现，通过 CAS （compare and swap）来完成
*/
func main() {
	conn := GetConnector()
	fmt.Printf("pointer of conn is %p \n", conn)
	conn2 := GetConnector()
	fmt.Printf("pointer of conn is %p \n", conn2)
}

